package com.xunmall.base.exception;

import java.io.IOException;

import com.fasterxml.jackson.core.type.TypeReference;
import com.xunmall.base.entity.MessageVo;
import org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder;
import org.springframework.context.annotation.Configuration;

import feign.Response;
import feign.codec.ErrorDecoder;
import feign.gson.GsonDecoder;
import org.springframework.http.ResponseEntity;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
	private final ResponseEntityDecoder decoder;
	
	public FeignErrorDecoder(){
		this.decoder = new ResponseEntityDecoder(new GsonDecoder());
	}

	@Override
	public Exception decode(String methodKey, Response response) {
		try {
			ResponseEntity<MessageVo> error = (ResponseEntity<MessageVo>) decoder.decode(response, new TypeReference<ResponseEntity<MessageVo>>() { }.getType());

			int status = response.status();
			switch (status) {
			case 301:
				return new MovedPermanentlyException(error.getBody(), methodKey);
			case 400:
				return new BadRequestException(error.getBody(), methodKey);
			case 401:
				return new UnauthorizedException(error.getBody(), methodKey);
			case 403:
				return new ForbiddenException(error.getBody(), methodKey);
			case 404:
				return new NotFoundException(error.getBody(), methodKey);
			case 500:
				return new BusinessException(error.getBody(), methodKey);
			default:
				return new BusinessException(error.getBody(), methodKey);
			}
		} catch (IOException e) {

			return new BusinessException(BaseException.ERR_9999, this);
		}
	}

}
